package com.chiang.security.springmvc.controller;

import com.chiang.security.springmvc.model.AuthenticationRequest;
import com.chiang.security.springmvc.model.UserDto;
import com.chiang.security.springmvc.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.xml.ws.RequestWrapper;

/**
 * @author : 765819328@qq.com
 * @version :
 * @date : Created in 2021/8/2 15:58
 * @description: 登录接口
 * @modified By:
 */
@RestController
public class LoginController {

    @Autowired
    AuthenticationService authenticationService;

    @RequestMapping(value = "/login", produces = "text/plain;charset=utf-8", method = {RequestMethod.GET, RequestMethod.POST})
    public String login(AuthenticationRequest authenticationRequest, HttpSession session) {
        UserDto userDto = authenticationService.authentication(authenticationRequest);
        //存入session
        session.setAttribute(UserDto.SESSION_USER_KEY, userDto);
        return userDto.getUsername() + "登录成功";
    }

    @GetMapping(value = "/logout", produces = "text/plain;charset=utf-8")
    public String logoout(HttpSession session) {
        session.invalidate();
        return "退出成功";
    }

    /**
     * 测试接口
     */
    @GetMapping(value = "/r/r1", produces = {"text/plain;charset=UTF-8"})
    public String r1(HttpSession session) {
        String fullName = null;
        Object object = session.getAttribute(UserDto.SESSION_USER_KEY);
        if (object == null) {
            fullName = "匿名";
        } else {
            UserDto user = (UserDto) object;
            fullName = user.getFullname();
        }
        return fullName + "访问资源r1";
    }

    /**
     * 测试接口
     */
    @GetMapping(value = "/r/r2", produces = {"text/plain;charset=UTF-8"})
    public String r2(HttpSession session) {
        String fullName = null;
        Object object = session.getAttribute(UserDto.SESSION_USER_KEY);
        if (object == null) {
            fullName = "匿名";
        } else {
            UserDto user = (UserDto) object;
            fullName = user.getFullname();
        }
        return fullName + "访问资源r1";
    }

}
